/**   
 * @Title: ActivityWebViewActivity.java 
 * @Package com.esun.rabbit2.viewer.mainact 
 * @Description: 活动用网页
 * @author: Billy Qigs@500wan.com   
 * @date: 2012-4-28 上午10:52:30  
 * Copyright: (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer;

import org.androidpn.client.Constants;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.user.NewLoginCommunicater;
import com.esun.rabbit2.viewer.mainact.mylotteryact.bindmobile.BindMobileUnBindAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.recharg.RechargeMenuPage;
import com.esun.ui.R;
import com.esun.util.log.EDebug;
import com.esun.util.magic.magic;

/**
 * @ClassName: ActivityWebViewActivity
 * @Description: 活动用网页
 * @author: Billy Qigs@500wan.com
 * @date: 2012-4-28 上午10:52:30
 * 
 */
public class ActivityWebViewActivity extends Activity {
	private NewLoginCommunicater userCommunicater;
	private Handler loginHandler;
	private RelativeLayout relativeProgress;
	private WebView webView;

	private String versionName;
	private String userName;
	private String userPwd;

	private final int LOGIN_SUCCEED = 1001;
	private final int LOGIN_FAIL = 1002;
	private static final String NAME = "name"; // 表元素,用户名
	private static final String PWD = "password"; // ..密码
	private static final String DBNAME = "db_arabbit2"; // 数据0库名
	private static final String TABLENAME = "users"; // 表名
	private String CURRENT_LAYOUT_NUM = "current_layout_num";
	private final int LOTTERYHALL = 2001;
	private final int RECHARGEMENU = 2002;
	private final int LOGINACT = 2003;
	private final int BINDMOBILE = 2004;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web_activity);

		initUI();

		initWebView();

		handlerInit();

		Intent intent = getIntent();
		// 获取web地址
		String url = intent.getStringExtra("url");
		EDebug.o(this, "activity url = " + url);
		// 加载网页
		webView.loadUrl(url);
	}

	// 获取版本号
	private void getVersionName() {
		try {
			versionName = this.getPackageManager().getPackageInfo("com.esun.ui", 0).versionName;
		} catch (Exception e) {
			versionName = Config.NULLMARK;
		}
	}

	// webview 初始化
	private void initWebView() {
		webView = (WebView) this.findViewById(R.id.activity_web_activity);
		// 设置支持js
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_OVERLAY);
		// js调用函数 实现客户端自动登录以及退出activity
		webView.addJavascriptInterface(new Object() {
			@SuppressWarnings("unused")
			public void login(final String username, final String userpwd) {

				// 自动登录
				loginThread(username, userpwd);

				// 结束activity
				EDebug.o(this, "结束webview");

				ActivityWebViewActivity.this.finish();
			}
		}, "login");

		webView.addJavascriptInterface(new toBindMobile_unBind_Class(), "toBindMobile_unBind");

		webView.addJavascriptInterface(new Object() {
			@SuppressWarnings("unused")
			public void jump(int action) {
				EDebug.o(this, "action = " + action);
				jumpFactory(action);
			}
		}, "jump");

		webView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				relativeProgress.setVisibility(View.GONE);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				relativeProgress.setVisibility(View.VISIBLE);
			}
		});
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
				Log.d("TAG", "alert");
				new AlertDialog.Builder(ActivityWebViewActivity.this).setTitle("").setMessage(message).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.confirm();
					}

				}).setCancelable(false).create().show();
				return true;
			}

		});

	}

	// 跳转绑定手机页面方法
	class toBindMobile_unBind_Class {
		public void toBindMobile_unBind(String mobileNum) {
			EDebug.o("print  by liuj ----------------------> mobileNum==============" + mobileNum);
			Intent intent = new Intent();
			intent.putExtra(Key.KEY_MOBILENUM, mobileNum);
			intent.putExtra(Key.KEY_STATE, Config.NUM0);
			intent.setClass(ActivityWebViewActivity.this, BindMobileUnBindAct.class);
			startActivity(intent);
			ActivityWebViewActivity.this.finish();
		}
	}

	// 界面初始化
	private void initUI() {

		relativeProgress = (RelativeLayout) findViewById(R.id.activity_web_act_progress);

	}

	// 登陆线程
	// 如果客户端没有登录，网页登陆则在客户端登陆
	// 如果客户端已登陆，则略过
	private void loginThread(final String username, final String userpwd) {
		EDebug.o(this, "print by billy  =>> username = " + username + " userpwd = " + userpwd);
		userName = username;
		userPwd = userpwd;
		new Thread() {
			@Override
			public void run() {
				try {
					EDebug.o(this, "开始登陆线程");
					if (userCommunicater == null) {
						userCommunicater = new NewLoginCommunicater();
					}
					getVersionName();

					SharedPreferences sharedPre = ActivityWebViewActivity.this.getSharedPreferences(Config.CLIENT_PREFERENCES, Context.MODE_PRIVATE);
					String userIMEI = sharedPre.getString(Constants.DEVICE_ID, Config.DEFAULT_LEAGUAGE_NUM);
					String IMEI = magic.getIMEI(ActivityWebViewActivity.this);

					boolean isLogin = userCommunicater.isLoginSucceed(username, userpwd, versionName, userIMEI, android.os.Build.MODEL, IMEI);
					String serverMessage = userCommunicater.getServerMsg();
					if (isLogin) {
						EDebug.o(this, "登陆成功");
						Message msg = loginHandler.obtainMessage(LOGIN_SUCCEED, serverMessage);
						loginHandler.sendMessage(msg);
					} else {
						EDebug.o(this, "登录失败");
						Message msg = loginHandler.obtainMessage(LOGIN_FAIL, serverMessage);
						loginHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					EDebug.o(this, "登陆异常");
					Message msg = loginHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					loginHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	private void handlerInit() {
		loginHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				// 登陆成功
				case LOGIN_SUCCEED:
					// 更新密码保护时间
					UserInfo.getUserInfo().setInputPasswordTime();
					UserInfo.getUserInfo().setNetWork(true);
					// 更新userinfo
					userCommunicater.updataUserInfo();
					Toast.makeText(ActivityWebViewActivity.this, UserInfo.getUserInfo().getUserName() + ",您已登录成功", Toast.LENGTH_SHORT).show();
					// 更新数据库
					updateDBInfo();

					break;

				case LOGIN_FAIL:
					break;

				case Config.CONNECTION_FAIL:
					break;

				default:
					break;
				}

			}

		};
	}

	// 更新数据库数据
	private void updateDBInfo() {
		// user TEXT,password TEXT,save TEXT
		EDebug.o(this, "updateDBInfo");
		ContentValues cv = new ContentValues();
		cv.put(NAME, userName);
		cv.put(PWD, userPwd);

		SQLiteDatabase db = this.openOrCreateDatabase(DBNAME, MODE_PRIVATE, null);

		db.update(TABLENAME, cv, "_id=?", new String[] { Config.NUM1 });
		db.close();
	}

	/**
	 * @Title: jumpToLotteryHall
	 * @Description: 跳转到购彩大厅
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void jumpToLotteryHall() {

		((MainAct) this.getParent()).setChildActivity(MainAct.LOTTERY_HALL_ACTIVITY);
		this.finish();

	}

	/**
	 * @Title: jumpToRechargeMenu
	 * @Description: 跳转到充值列表页面
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void jumpToRechargeMenu() {

		// MainAct.tab_host.setCurrentTab(3);
		ActivityWebViewActivity.this.startActivity(new Intent(this, RechargeMenuPage.class));
		this.finish();

	}

	/**
	 * @Title: jumpToLoginAct
	 * @Description: 跳转到登陆页面
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void jumpToLoginAct() {

		this.finish();
		ActivityWebViewActivity.this.startActivity(new Intent(this, LoginAct.class));

	}

	/**
	 * @Title: jumpToBindMobile
	 * @Description: 这里用一句话描述这个方法的作用
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void jumpToBindMobile() {

		this.finish();
		ActivityWebViewActivity.this.startActivity(new Intent(this, BindMobileUnBindAct.class).putExtra(Key.KEY_MOBILENUM, Config.NULLMARK).putExtra(Key.KEY_STATE, Config.NUM1));

	}

	/**
	 * @Title: jump
	 * @Description: webview跳转到客户端指定界面的方法
	 * @param: @param action 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void jumpFactory(int action) {

		switch (action) {
		case LOTTERYHALL:
			EDebug.o(this, "跳转到购彩大厅");
			jumpToLotteryHall();
			break;

		case RECHARGEMENU:
			EDebug.o(this, "跳转到充值列表");
			jumpToRechargeMenu();
			break;

		case LOGINACT:
			EDebug.o(this, "结束活动webview");
			jumpToLoginAct();
			break;

		case BINDMOBILE:
			EDebug.o(this, "结束活动webview");
			jumpToBindMobile();
			break;

		default:
			EDebug.o(this, "结束活动webview");
			break;
		}
		EDebug.o(this, "结束活动webview");
		ActivityWebViewActivity.this.finish();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webView.canGoBack()) {
				webView.goBack();
			} else {
				ActivityWebViewActivity.this.finish();
			}
		}

		return true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
	}
}
